<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>BFS</title>
  </head>
  <body>
    <h1>广度优先遍历（Breadth-First Search, BFS）是一种按层次遍历树或图的算法，它从根节点（或起始节点）开始，先访问所有相邻节点，再逐层向外扩展。</h1>
    <script>
      const tree = {
        name: "A",
        children: [
          {
            name: "B",
            children: [{ name: "E" }, { name: "F" }],
          },
          { name: "C" },
          {
            name: "D",
            children: [{ name: "G" }, { name: "H" }],
          },
        ],
      };

      function bfs(root) {
        const queue = [root]; // 初始化队列，放入根节点
        while (queue.length > 0) {
          const node = queue.shift(); // 取出队首节点
          console.log(node.name); // 访问该节点

          // 将该节点的所有子节点加入队列
          if (node.children) {
            for (const child of node.children) {
              queue.push(child);
            }
          }
        }
        return queue;
      }

      bfs(tree);
    </script>
  </body>
</html>
